﻿namespace NJQuery {
	using System;
	using System.Collections.ObjectModel;
	using System.Web.UI;
	using System.Globalization;

	/// <summary>
	/// Manages a set of <see cref="DialogButtonBase"/> items for a container control
	/// </summary>
	public class DialogButtonCollection : GroupControlCollection<DialogButtonBase>, IClientHash {


		#region Constructors

		/// <summary>
		/// Initializes a new instance of the <see cref="DialogButtonCollection"/> class.
		/// </summary>
		/// <param name="container">The group control that the <see cref="DialogButtonCollection" /> is contained within.</param>
		/// <exception cref="ArgumentNullException">Container cannot be null.</exception>
		public DialogButtonCollection(GroupControlContainer container) : base(container) { }

		#endregion


		#region Methods: Rendering hooks

		/// <summary>
		/// Creates the properties object that will be rendered as the jQuery UI initialization options.
		/// This method is used primarily by control developers.
		/// </summary>
		/// <param name="properties">A <see cref="PropertyCollection"/> object that will become the jQuery UI initialization options.</param>
		protected virtual void AddInitProperties(PropertyCollection properties) {

			const string emptyFunction = "function() { }";

			foreach(DialogButtonBase button in this) {
				if(!button.Visible) continue;

				ScriptBuilder script = properties.CreateChildScript();
				button.RenderOnClickScriptInternal(script);

				properties.AddScript(string.Format(CultureInfo.InvariantCulture, "'{0}'", ScriptBuilder.JavaScriptStringEncode(button.Text)),
					script.Length == 0 ? emptyFunction : script.ToString());

			}

		}

		/// <summary>
		/// Returns a literal JavaScript value used to represent the server value on the client.
		/// </summary>
		/// <param name="indent">The indentation level of the client script.</param>
		/// <returns>The client script value.</returns>
		public string ToClientSource(int indent) {
			PropertyCollection childProperties = new PropertyCollection(indent);
			AddInitProperties(childProperties);
			return childProperties.ToClientSource();
		}

		#endregion


	}

}